<?php

require_once "config.php";
session_start();
// echo $_SESSION['Address']['Id'];exit;
// print_r($_SESSION['Address']);exit;
$userinfo = empty($_GET['userinfo']) ? '' : $_GET['userinfo'];
if(!empty($_SESSION['Member_info'][0]['openid'])){
    $member_sql = $mysql->query("select * from dyspw_member where openid = '{$_SESSION['Member_info'][0]['openid']}'");
    $mem_info = $member_sql->fetch_all(MYSQLI_ASSOC);
}
if(!empty($userinfo) ){
  $userinfo = rawurldecode($userinfo);
  $userinfo = json_decode($userinfo,true);
  $userinfo['headimgurl'] = str_replace('http','https',$userinfo['headimgurl']);
  /*进入页面获取信息*/
  // echo $userinfo['openid'];
  // print_r($userinfo);exit;
  // $sql="select * from dyspw_member where openid = '".$userinfo['openid']."'";
  $sql="select * from dyspw_member where unionid = '".$userinfo['unionid']."'";
  $member = mysqli_query($mysql, $sql);
  $mem_info = $member->fetch_all(MYSQLI_ASSOC);
  if(empty($mem_info)){
	  $arr_state = 'false';
//      echo '<img src="images/c621c304ee31a7324844833422b5fde.png" alt="" style="width:100%; position: fixed;height: 100%;z-index: 999;">';
//      return;
      $time = time();
      $add_sql = "INSERT INTO dyspw_member(username, openid, sex,regtime, logintime, avatar, live_prov, live_city, live_country,unionid)
                VALUES  ('".$userinfo['nickname']."','".$userinfo['openid']."','".$userinfo['sex']."',".$time.",".$time.",'".$userinfo['headimgurl']."','".$userinfo['province']."','".$userinfo['province']."','".$userinfo['city']."','".$userinfo['unionid']."')";
      $add_meminfo = $mysql->query($add_sql);
      if(!empty($add_meminfo)){
        $sel_sql="select * from dyspw_member where unionid = '".$userinfo['unionid']."'";
        $sel_meminfo = mysqli_query($mysql, $sel_sql);
        $sel_meminfo = $sel_meminfo->fetch_all(MYSQLI_ASSOC);
        $_SESSION['Member_info'] = $sel_meminfo;
      }
  }else{
    $_SESSION['Member_info'] = $mem_info;
  }
}elseif (empty($_SESSION['Member_info'][0]['openid']) || empty($mem_info)) {
    require_once "weixin_info.php";
}
function unicodeDecode($unicode_str)
{
    $json = '{"str":"' . $unicode_str . '"}';
    $arr = json_decode($json, true);
    if (empty($arr)) return '';
    return $arr['str'];
}
require_once "Git_City.php";
// echo $_SESSION['Member_info'][0]['id'];exit;
//首页推荐逻辑
$uid = $_SESSION['Member_info'][0]['id'];
$label = empty($_GET['label']) ? '' : $_GET['label'];
if ($_GET['keyword']) {
    $key = unicodeDecode($_REQUEST['keyword']);
    $result = $mysql->query("select * from dyspw_weblink where webnote LIKE '%" . $key . "%' or webname LIKE '%" . $key . "%' ORDER BY posttime DESC");
    $rows = $result->fetch_all(MYSQLI_ASSOC);
}elseif(!empty($label) && $label == 'jiabohui'){
    $label_sql = $mysql->query("select id from dyspw_member where label = 'jiabohui'");
    $label_mem = $label_sql->fetch_all(MYSQLI_ASSOC);
    foreach ($label_mem as $key => $val) {
        $two_sql = $mysql->query("select id from dyspw_member where shop_son_id = '{$val['id']}'");
        $two_mem = $two_sql->fetch_all(MYSQLI_ASSOC);
    }
    foreach ($two_mem as $key => $val) {
        $label_mem[] = $val;
    }
    $rows = array();
    foreach ($label_mem as $key => $val) {
        $web_sql = $mysql->query("select * from dyspw_weblink where u_id = {$val['id']} ORDER BY id DESC");
        $web[] = $web_sql->fetch_all(MYSQLI_ASSOC);
    }
    foreach ($web as $key => $val) {
        foreach ($val as $k => $v) {
            $rows[] = $v;
        }
    }
    $last_ages = array_column($rows,'id');
    array_multisort($last_ages ,SORT_DESC,$rows);
    // $rows = array_multisort($rows, SORT_DESC);
    // array_multisort($last_names,SORT_DESC,$data);
}elseif(!empty($label) && $label == 'tejia'){
    $label_sql = $mysql->query("select * from dyspw_weblink where goods_id != '' and goods_id != 0 ORDER BY id DESC");
    $rows = $label_sql->fetch_all(MYSQLI_ASSOC);
    // print_r($rows);exit;
}elseif (!empty($_GET['lat']) && !empty($_GET['lng'])) {
        $lat =  $_GET['lat'];
        $lng = $_GET['lng'];
        $sql = "SELECT id,lng,lat,siteid,classid,parentid,parentid,webname,webname,picurl,linkurl,hits,hits,orderid,posttime,checkinfo,nickname,avatar,openid,u_id,goods_id,shop_id,report,is_vip,
                    ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000)
                    AS juli FROM dyspw_weblink where lat != '' and lng != ''  ORDER BY juli Asc";
        $result = $mysql->query($sql);
        $rows = $result->fetch_all(MYSQLI_ASSOC);
        // print_r($rows);exit;
        // $sql = "SELECT id,lng,lat,
        // ROUND(6378.138*2*ASIN(SQRT(POW(SIN((lat1*PI()/180-lat*PI()/180)/2),2)+COS(lat1*PI()/180)*COS(lat*PI()/180)*POW(SIN((lng1*PI()/180-lng*PI()/180)/2),2)))*1000)
        // AS
        //  juli
        // FROM address having juli > 500
        // ORDER BY juli Asc
        // LIMIT 100";
        // echo $sql;exit;

} else {

    if (empty($uid)) {
        $result = $mysql->query("select * from dyspw_weblink ORDER BY hits DESC,posttime DESC");
        $rows = $result->fetch_all(MYSQLI_ASSOC);
    } else {
        $u_info_q = $mysql->query("select pianhao,history from dyspw_member where id=" . $uid);
        $u_info_arr = $u_info_q->fetch_all(MYSQLI_ASSOC);
        $u_info = $u_info_arr[0];
        $history = $u_info['history'];
        if(empty($history)){
        	$history = '1';
        }
//        var_dump($u_info);exit;
        //分页逻辑基础设置
        $page = 0;
        $n_page = 1;

        $pianhao = $u_info['pianhao'];
        if ($_POST['page']) {
            $page = $_POST['page'];
            $n_page = $page*2+1;
            //第一次进入
            $rows_for = array();
//        for ($page = 0; $page <= $all_count; $page++) {
            //用户发布的最新一条
//            $result0 = $mysql->query("select * from dyspw_weblink where u_id=" . $uid . " ORDER BY posttime DESC,hits DESC limit 1");
//            $rows0 = $result0->fetch_all(MYSQLI_ASSOC);
//        $rows0 = array_slice($rows0,1,1);
            //按用户偏好和点击量获取一条最高的
            $result1 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and classid=" . $pianhao . " and id not in (".$history.") ORDER BY hits DESC limit " . $page * 2 . ",2");
            $rows1 = $result1->fetch_all(MYSQLI_ASSOC);
//            $rows1 = array_slice($rows1,$page,1);
            //按用户偏好和时间倒序获取一条最新的
            $result2 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and classid=" . $pianhao . " and id not in(".$history.") ORDER BY posttime DESC limit " . $page * 2 . ",2");
            $rows2 = $result2->fetch_all(MYSQLI_ASSOC);
//            $rows2 = array_slice($rows2,$page,1);

            $result6 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and is_vip in (2,3) ORDER BY hits DESC,posttime DESC limit " . $page * 2 . ",1");
            $rows6 = $result6->fetch_all(MYSQLI_ASSOC);
//            $rows4 = array_slice($rows4,$page,1);

            //按照点击量获取一条最多的
            $result3 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and id not in (".$history.") ORDER BY hits DESC limit " . $page * 2 . ",2");
            $rows3 = $result3->fetch_all(MYSQLI_ASSOC);
//            $rows3 = array_slice($rows3,$page,1);
            //按照上传时间获取一条最新的
            $result5 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and id not in (".$history.") ORDER BY posttime DESC limit " . $page * 2 . ",2");
            $rows5 = $result5->fetch_all(MYSQLI_ASSOC);
//            $rows5 = array_slice($rows5,$page,1);
            //获取一条拍客的广告视频
            $result4 = $mysql->query("select * from dyspw_weblink  where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and is_vip in (2,3) ORDER BY hits DESC,posttime DESC limit " . $n_page . ",1");
            $rows4 = $result4->fetch_all(MYSQLI_ASSOC);
//            $rows4 = array_slice($rows4,$page,1);
            $rows_for = array_merge($rows_for, /*$rows0, */ $rows1, $rows2, $rows6, $rows3, $rows5, $rows4);
//            $rows_for = array_merge($rows_for, $rows_page);
//        }
//        $rows_all = array_merge($rows0, $rows_for);
//            $rows = array_unique($rows_for, SORT_REGULAR);//返回数据的去重处理
            $back_info = ['code' => 200, 'msg' => '获取第' . $page . "页信息成功", 'data' => $rows_for];
            echo json_encode($back_info);
            die;
        } else {//若非请求数据时（即刷新进入页面）
            // echo $_SESSION['Address']['id'];exit;
            //第一次进入
            $rows_for = array();
//        for ($page = 0; $page <= $all_count; $page++) {
            //用户发布的最新一条
            $result0 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and  u_id=" . $uid . " ORDER BY posttime DESC,hits DESC limit 1");
            $rows0 = $result0->fetch_all(MYSQLI_ASSOC);
//        $rows0 = array_slice($rows0,1,1);
            //按用户偏好和点击量获取一条最高的
            $result1 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and classid=".$pianhao." and id not in (".$history.") ORDER BY hits DESC limit ".$page.",2");
            $rows1 = $result1->fetch_all(MYSQLI_ASSOC);
//            $rows1 = array_slice($rows1,$page,1);
            //按用户偏好和时间倒序获取一条最新的
            $result2 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and classid=" . $pianhao . " and id not in (".$history.") ORDER BY posttime DESC limit " . $page . ",2");
            $rows2 = $result2->fetch_all(MYSQLI_ASSOC);
//            $rows2 = array_slice($rows2,$page,1);
            //第一个商家视频
            $result6 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and is_vip=3 and id not in (".$history.") ORDER BY hits DESC,posttime DESC limit " . $page . ",1");
            $rows6 = $result6->fetch_all(MYSQLI_ASSOC);
//            $rows4 = array_slice($rows4,$page,1);
            //按照点击量获取一条最多的
            $result3 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and id not in (".$history.") ORDER BY hits DESC limit " . $page . ",2");
            $rows3 = $result3->fetch_all(MYSQLI_ASSOC);
//            $rows3 = array_slice($rows3,$page,1);
            //按照上传时间获取一条最新的
            $result5 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and id not in (".$history.") ORDER BY posttime DESC limit " . $page . ",2");
            $rows5 = $result5->fetch_all(MYSQLI_ASSOC);
//            $rows5 = array_slice($rows5,$page,1);
            //获取一条拍客的广告视频
            $result4 = $mysql->query("select * from dyspw_weblink where (address_id = '{$_SESSION['Address']['Id']}' or address_id = 0) and is_vip in (2,3) and id not in (".$history.") ORDER BY hits DESC,posttime DESC limit 1,1");
            $rows4 = $result4->fetch_all(MYSQLI_ASSOC);
//            $rows4 = array_slice($rows4,$page,1);
            $rows_for = array_merge($rows_for, $rows0, $rows1, $rows2, $rows6, $rows3, $rows5, $rows4);
//            $rows_for = array_merge($rows_for, $rows_page);
//        }
//        $rows_all = array_merge($rows0, $rows_for);
            $rows = array_unique($rows_for, SORT_REGULAR);
            // print_r($rows );
        }
    }
}

//var_dump($rows);exit;
require_once "jssdk.php";
$jssdk = new JSSDK("wx16320d7479a5774c", "e111c965e8d4ba6a2ff1a99724f6d573");
$signPackage = $jssdk->GetSignPackage();
?>

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <title>首页</title>
    <meta name="keywords" content=""/>
    <meta name="description" content=""/>
    <meta name="full-screen" content="yes">
    <meta name="x5-fullscreen" content="true">
    <link rel="stylesheet" href="css/core.css?version=1.6">
    <link rel="stylesheet" href="css/editStyle.css?version=1.6">
    <link rel="stylesheet" href="css/dropload.css?version=1.6">
    <script src="js/jquery-2.2.4.min.js" type="text/javascript"></script>
    <script src="js/jquery.cookie.js" type="text/javascript"></script>
    <script src="js/layer/layer.js" type="text/javascript"></script>
    <script src="js/dropload.js" type="text/javascript"></script>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <script type="text/javascript" src="//webapi.amap.com/maps?v=1.4.1&key=fedad41056b27c3e8cc5eaca216434e9"></script>
	<script src="js/dsbridge.js" type="text/javascript"></script>
    <!-- <script src="https://cdn.bootcss.com/vConsole/3.2.2/vconsole.min.js"></script>
    <script>var vConsole = new VConsole();</script> -->
    <style>
        .header-box .header-search .search-fl input {
            padding: 0 40px 0 5%;
            background: #c2c2c2;
        }

        .s_bt {
            width: 24px;
            margin-left: -40px;
            margin-top: 3px;
            -webkit-z-index: 99;
            -moz-z-index: 99;
            z-index: 99;
        }

        .opacity{
            -webkit-animation: opacity 0.3s linear;
            animation: opacity 0.3s linear;
        }

        @-webkit-keyframes opacity {
            0% {
                opacity:0;
            }
            100% {
                opacity:1;
            }
        }

        @keyframes opacity {
            0% {
                opacity:0;
            }
            100% {
                opacity:1;
            }
        }
        .video-box {
            width: 100%;
            height: calc(100% - 80px);
            overflow-x: hidden;
            overflow-y: scroll;
        }

        .header-box,.main,section,body,html,.boxdiv{
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        .fl{
            text-align: left;
        }
    </style>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cb5d49b07e0a753dc8ee27ba2c73495d";
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(hm, s);
})();
</script>
</head>
<body style="background:#f1f1f1;overflow: hidden;">
<?php if($app_state == 'false'){ ?>
	<!-- <img src="images/c621c304ee31a7324844833422b5fde.png" alt="" style="width:100%; position: fixed;height: 100%;z-index: 999;"> -->
    <!-- <img src="images/tejia.gif" alt="" style="width:100%; position: fixed;height: 100%;z-index: 999;"> -->
<?php } ?>

<!--此图片必须放在body标签的最前面，且高度必须为屏幕宽度的80%  -->
<img src="" style="position:absolute; top:0; left:0;width: 30px;height:30px;z-index:-1;opacity: 0; " class="iiimg">

<div class="boxdiv">
    <section style="padding-bottom:50px;">
        <div class="main">
            <div class="header-box">
                <div class="header-nav cl">
                    <ul class="cl">
                        <li style="text-align:center;">
                            <a href="javascript:void(0);"  class="nearby">附近</a>
                            <input type="hidden" name="nearby_lat" value="">
                            <input type="hidden" name="nearby_lng" value="">
                        </li>
                        <li><a href="index.php">推荐</a></li>
                        <li><a href="follow.php">关注</a></li>
                    </ul>
                    <script type="text/javascript">
                        $(function(){
                            $(".nearby").click(function(){
                                if(window.navigator.userAgent == 'AndroidNative'){ // 原生app将用户id传送给原生
                                    var location = dsBridge.call("getLocation", 'getLocation');
                                    console.log('测试获取定位：' + location)
                                    if (location) {
                                        console.log('测试获取定位PARSE：')
                                        console.log(JSON.parse(location))
                                        console.log('index.php?lat='+JSON.parse(location).latitude+'&lng='+JSON.parse(location).longitude)
                                        window.location.href='index.php?lat='+JSON.parse(location).latitude+'&lng='+JSON.parse(location).longitude;
                                        console.log('重定向')
                                    } else {
                                        alert('未获取到位置信息');
                                    }
                                } else if (window.navigator.userAgent == 'IosNative') {
                                    dsBridge.call("getLocation", "getLocation", function (location) {
                                        // alert('测试获取定位：' + JSON.parse(location).latitude)
                                        console.log('测试获取定位：' + JSON.parse(location))
                                        if (location) {
                                            console.log('测试获取定位PARSE：' + JSON.parse(location))
                                            window.location.href='index.php?lat='+JSON.parse(location).latitude+'&lng='+JSON.parse(location).longitude;
                                        } else {
                                            alert('未获取到位置信息');
                                        }
                                    });
                                    // var location = dsBridge.call("getLocation", 'getLocation');
                                } else {
                                    var nearby_lat = $("input[name='nearby_lat']").val();
                                    var nearby_lng = $("input[name='nearby_lng']").val();
                                    if(nearby_lat == '' && nearby_lng == ''){
                                        alert('未获取到位置信息');
                                    }else{
                                        window.location.href='index.php?lat='+nearby_lat+'&lng='+nearby_lng;
                                    }
                                }

                            })
                        })
                    </script>
                </div>
                <div class="header-search cl">
                    <div class="search-fr">

                        <!-- <a href="http://console.nuoyun.tv/Mobile/Index/index">直播</a> -->
                        <a href="javascript: void(0);" class="BindShare"><img src="images/header-wx.png"/>分享</a>
                    </div>
                    <div class="search-fl">
                        <input type="text" placeholder="搜索更多话题" id="keyword" value="">
                        <img src="images/icon18.png" alt="搜索" class="s_bt" onclick="getSearch()">
                    </div>


                </div>
                <div id="showVideo" style="display:none;"></div>
                <img id="back_img" src="" alt="" style="display:none;">
                <input type="hidden" id="p1" name="p1" value="">
                <div class="video-box">
                    <!-- <a href="index.php?label=jiabohui"><img src="images/jiabohui.gif" alt="" style="width: 70px;position: fixed;top: 150px;z-index: 100;right: 0px;"></a> -->
                    <a href="index.php?label=tejia"><img src="images/tejia.gif" alt="" style="width: 70px;position: fixed;top: 150px;z-index: 100;right: 0px;"></a>
                    <!-- 下拉获取更多 start -->
                    <ul class="cl">
                        <?php foreach ($rows as $k => $v) { ?>
                            <?php if ($v['checkinfo'] == 'true') { ?>
                                <li style="position: relative;">
                                    <a href="content.php?id=<?php echo $v['id']; ?>">
                                        <div class="" style="position: relative;">
                                            <img src="<?php echo $v['linkurl'] . "?vframe/jpg/offset/1/w/368/h/640/rotate/auto"; ?>"
                                                 class="">
                                            <p style="    position: absolute;bottom: 0px;">
                                                <?php if (!empty($v['lng']) && !empty($v['lat'])) { ?>
                                                    <img src="./images/adress.png" alt="" style="width: 25px;">
                                                    <span id="juli<?php echo $v['id']; ?>" class="julitxt"
                                                          lng="<?php echo $v['lng']; ?>" lat="<?php echo $v['lat']; ?>"
                                                          style="color: #fff;font-size: 12px;letter-spacing: 1px;"></span>
                                                <?php } ?>
                                            </p>
                                        </div>
                                        <h2 style="font-size: 11px ;   text-align: left;line-height: 30px;"><?php echo $v['webnote'] ?></h2>
                                        <div class="video-desc">
                                            <div class="fl" style="    width: 70%;height: 25px;overflow: hidden;"><img
                                                        src="<?php echo $v['avatar'] ?>"/><?php echo $v['webname'] ?>
                                            </div>
                                            <em><?php echo $v['hits'] ?></em></div>
                                    </a>
                                    <?php if(!empty($label) && $label == 'jiabohui'){ ?>
                                        <img src="images/jiabohui_icon.png" alt="" style="width: 60px;position: absolute;top: 0px;right: 0px;">
                                    <?php } ?>
                                    <?php if(!empty($v['goods_id']) && $v['goods_id'] != 0){ ?>
                                        <img src="images/tejia_icon.png" alt="" style="width: 60px;position: absolute;top: 0px;right: 0px;">
                                    <?php } ?>
                                </li>
                            <?php } ?>
                        <?php } ?>
                    </ul>
                    <!-- 下拉获取更多 end -->
                </div>
            </div>
    </section>
    <footer>
        <ul class="cl">
            <li><a href="index.php">首页</a></li>
            <li><a href="fenlei.php">分类</a></li>
            <li>
                <a href="baishe.php" class="btn-baise">拍</a>
            </li>
            <li><a href="shopping.php">商城</a></li>
            <li><a href="member.php">我</a></li>
        </ul>
    </footer>
</div>

<!-- 编辑窗口 start -->
<div class="box-curtain"></div>
<div class="share-info-box">
    <h2>分享内容编辑</h2>
    <div class="form">
        <!-- 图片上传 start-->
        <div class="form-item"
             style="width: 100px;height: 140px;overflow:hidden;display: flex;justify-content: center;flex-flow: column;">
            <div class="fileDiv">
                <div class="filebox" onclick="upFile();">
                    <img src="" alt="上传图片" id="fileImg">
                    <!-- <input type="hidden" name="share_img" value="" class="hideInput" onchange="changepic(this)"> -->
                </div>
            </div>
            <div onclick="upFile();" class="reloadDiv">
                <span>点击替换图片</span>
            </div>
            <!-- 隐藏域 -->
            <input type="file" id="file" class="filepath" onchange="changepic(this)"
                   accept="image/jpg,image/jpeg,image/png,image/PNG" hidden>
            <canvas id="canvas" style="display: none;"></canvas>
        </div>
        <!-- 图片上传 end-->

        <div class="rightbox">
            <div class="form-item">
                <input type="text" name="title" value="" class="title-input" placeholder="">
            </div>
            <div class="form-item">
                <textarea rows="4" class="desc-input" placeholder=""></textarea>
            </div>
        </div>
    </div>
    <?php if ($_SERVER['HTTP_USER_AGENT'] == 'AndroidNative' || $_SERVER['HTTP_USER_AGENT'] == 'IosNative') { ?>
        <input type="submit" value="分享" class="save">
        <?php
        } else { ?>
        <input type="submit" value="保存" class="save">
    <?php }?>
</div>
<!-- 编辑窗口 end -->


<script type="text/javascript">

    // **************
    // 将本页视频选择功能移到第二页面操作， 此页相关代码该删除的删除
    // **************
    var file = ''; //图片文件名
    var aaa;
    var _img = '',
        target_width = '',
        target_height = ''; //压缩后图片宽高

    // 页数
    var page = 0;

    var _title = '5拍8视频首页',
        share_desc = '5拍8同城小视频，你我相伴，快乐相随',
        _imgURL = 'https://5p8.fyh5p8.com/xiaochengxu/images/20200414175522.png',
        _link = 'https://5p8.fyh5p8.com/xiaochengxu/index.php';  //需要分享的信息

    var n_title = '<?php if (!empty($share)) {
            echo $share[0]['title'];
        } ?>', //需要分享的标题
        n_imgurl = '<?php if (!empty($share)) {
            echo $share[0]['img_url'];
        } ?>', //需要分享的缩略图
        n_desc = '<?php if (!empty($share)) {
            echo $share[0]['desc'];
        } ?>', //需要分享的描述
        n_link = 'content.php?id=<?php echo $share[0]['id'];?>'; //需要分享的链接

    if (n_title != '') {
        document.title = n_title;
        _title = document.title;
        var meta = document.getElementsByTagName('meta');
        for (i in meta) {
            if (typeof meta[i].name != "undefined" && meta[i].name.toLowerCase() == "description") {
                share_desc = meta[i].content;
                share_desc = n_desc; //自定义描述
            }
        }
        _imgURL = n_imgurl; //自定义图片
        _link = n_link;//链接
    }

    $('.iiimg').attr('src', _imgURL);
    //编辑框数据
    $('#fileImg').attr('src', _imgURL);
    $('.title-input').attr('placeholder', _title);
    $('.desc-input').attr('placeholder', share_desc);

    $(function () {
        var len = $('.video-box .cl li').length;
        if (len == 0) {
            layer.open({
                content: '没有匹配的视频标题！',
                skin: 'msg',
                time: 2 //2秒后自动关闭
            });
            setTimeout(() => {
                window.location.href = "https://5p8.fyh5p8.com/xiaochengxu/index.php";
            }, 2200);
        }

        getaddre();

        //显示分享插件
        $(".BindShare").click(function () {
            $('.share-info-box').slideDown(300);
            $('.box-curtain').show();
        });

        //隐藏遮幕
        $(".box-curtain").click(function () {
            $('.box-curtain').hide();
            $('.share-info-box').slideUp(300);
            $('.comment-info-box').slideUp(300);
            $('.contact-info-box').hide();
        })

        /*判断手机端左滑右滑动*/
        $("body").on("touchstart", function (e) {
            startX = e.originalEvent.changedTouches[0].pageX,
                startY = e.originalEvent.changedTouches[0].pageY;
        });
        $("body").on("touchend", function (e) {
            moveEndX = e.originalEvent.changedTouches[0].pageX,
                moveEndY = e.originalEvent.changedTouches[0].pageY,
                X = moveEndX - startX,
                Y = moveEndY - startY;

            //右滑
            if (X < -100) {
                location.href = 'fenlei.php';
            }
            //
            //左滑
            if (X > 100) {
                location.href = 'fenlei.php';
            }
            //    //右滑
            //    else if ( X < 0 ) {
            //        location.href = 'fenlei.php';
            //    }
            // //下滑
            // else if ( Y > 0) {
            //     console.log('下滑');
            // }
            // //上滑
            // else if ( Y < 0 ) {
            //     console.log('上滑');
            // }
            // //单击
            // else{
            //     console.log('单击');
            // }
        });

        // $(".btn-baise").click(function(){
        //     $('.btn-baise-box').slideDown(300);
        // });

        // $(".btn-close").click(function(){
        //     $('.btn-baise-box').slideUp(300);
        // });

        // // 隐式创建一个input控件，然后实现直接访问相册
        // var inputUploadObj = '';
        // $(".btn-camera").click(function(){
        //     layer.open({content:"请稍等正在跳转",skin:'msg',time:5});
        //     if($("input[type='file']").length > 0){
        //         $("input[type='file']").remove();
        //     }
        //     inputUploadObj = document.createElement('input')
        //     inputUploadObj.setAttribute('id', 'input_upload_ID');
        //     inputUploadObj.setAttribute('type', 'file');
        //     // 添加这个属性，就可以唤起相机的功能
        //     inputUploadObj.setAttribute('capture', 'camera');
        //     // 这里如果不加属性 accept 是 "image/*" 或者 "video/*"，就默认打开摄像头，既可以拍照也可以录像
        //     inputUploadObj.setAttribute('accept', 'video/*');
        //     inputUploadObj.setAttribute("style", 'visibility:hidden');
        //     // 这里将创建的隐式input控件拼接到body的最后面，会增加页面的长度，所以要在适当的时候，移除掉这个隐式创建的input控件
        //    document.body.appendChild(inputUploadObj);
        //     // 这里是模拟点击了input控件
        //     inputUploadObj.click();
        //     $("#input_upload_ID").change(function () {
        //         var formFile = new FormData();
        //         formFile.append("file", $(this)[0].files[0]); //加入文件对象
        //         $.ajax({
        //             url:'fileup.php',
        //             data:formFile,
        //             dataType:'json',
        //             type:'post',
        //             processData: false,
        //             contentType: false,
        //             success:function (data) {
        //                 if(data.code==1){
        //                     location.href="baishe.php?url="+data.msg;
        //                 }else{
        //                     alert(data.msg)
        //                 }
        //             }

        //         })
        //     })
        // });

        // $(".btn-files").click(function(){
        //     if($("input[type='file']").length > 0){
        //         $("input[type='file']").remove();
        //     }
        //     inputUploadObj = document.createElement('input')
        //     inputUploadObj.setAttribute('id', 'input_upload_ID');
        //     inputUploadObj.setAttribute('type', 'file');
        //     // 添加这个属性，就可以唤起相机的功能
        //     inputUploadObj.setAttribute("style", 'visibility:hidden');
        //     // 这里将创建的隐式input控件拼接到body的最后面，会增加页面的长度，所以要在适当的时候，移除掉这个隐式创建的input控件
        //     document.body.appendChild(inputUploadObj);
        //     // 这里是模拟点击了input控件
        //     inputUploadObj.click();
        //     $("#input_upload_ID").change(function () {
        //         var videoFile = this.files[0];
        //         var url = URL.createObjectURL(videoFile);
        //         var showVideo = document.getElementById("showVideo");
        //         var htmls = ' <video  id="video" height="auto" controls> <source src="' + url + '">您的浏览器不支持 HTML5 video 元素。</video>';
        //         showVideo.innerHTML = htmls;
        //         jiequ();
        //         layer.open({content:"请稍等正在跳转",skin:'msg',time:5});
        //         var formFile = new FormData();
        //         formFile.append("file", $(this)[0].files[0]); //加入文件对象
        //         $.ajax({
        //             url:'fileup.php',
        //             data:formFile,
        //             dataType:'json',
        //             type:'post',
        //             processData: false,
        //             contentType: false,
        //             success:function (res) {
        //                 if(res.code==1){
        //                     location.href="baishe.php?url="+res.msg;
        //                 }else{
        //                     alert(res.msg);
        //                 }
        //             }

        //         })
        //     })
        // });


        wx.config({
            debug: false,
            appId: '<?php echo $signPackage["appId"];?>',
            timestamp: <?php echo $signPackage["timestamp"];?>,
            nonceStr: '<?php echo $signPackage["nonceStr"];?>',
            signature: '<?php echo $signPackage["signature"];?>',
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'showAllNonBaseMenuItem',
                'updateAppMessageShareData'
            ]
        });
        wx.showAllNonBaseMenuItem();
        wx.ready(function () {
            wx.onMenuShareAppMessage({
                // link: _link,
                link: '',
                imgUrl: _imgURL,
                desc: share_desc,
                title: _title,
                success: function (data) {
                    //alert('分享完成!')
                },
                cancel: function () {
                }
            });
        });

        //提交保存前
        $('.save').click(function () {
            var placetitle = $('.title-input').attr('placeholder');
            var placedesc = $('.desc-input').attr('placeholder');
            var title = $('.title-input').val();
            var desc = $('.desc-input').val();
            var shareTitle = ''
            var shareDesc = ''

            if (title == '' || title.replace(/(^s*)|(s*$)/g, "").length == 0) {
                if (placetitle == '') {
                    layer.open({
                        content: '请先输入标题！',
                        skin: 'msg',
                        time: 2 //2秒后自动关闭
                    });
                } else {
                    $('.title-input').val(placetitle);
                    shareTitle = placetitle
                }
            } else {
                shareTitle = title
            }

            if (desc == '' || desc.replace(/(^s*)|(s*$)/g, "").length == 0) {
                if (placedesc == '') {
                    layer.open({
                        content: '请先输入描述！',
                        skin: 'msg',
                        time: 2 //2秒后自动关闭
                    });
                } else {
                    $('.desc-input').val(placedesc);
                    shareDesc = placedesc
                }
            } else {
                shareDesc = desc
            }

            if ($('#fileImg').attr("src") == '') {
                layer.open({
                    content: '请先上传图片！',
                    skin: 'msg',
                    time: 2 //2秒后自动关闭
                });
                return false;
            }
            //提交接口 判断是否APP
            if(window.navigator.userAgent == 'AndroidNative'){
                // window.location.protocol + "//" + window.location.host + "/xiaochengxu/" +
                dsBridge.call("indexShare", {img: _imgURL,  title: shareTitle, content:shareDesc, link:_link});
                // javascript:android.indexShare(_imgURL, title, desc, _link);
            } else if (window.navigator.userAgent == 'IosNative') {
                dsBridge.call("indexShare", {img: _imgURL,  title: shareTitle, content:shareDesc, link:_link});
                // window.webkit.messageHandlers.indexShare.postMessage({img: _imgURL, title: title, content:desc, link:_link});
            } else {
                loadData();
            }
        });

         // 下拉加载
        $('.video-box').dropload({
            // scrollArea : window,
            domDown: {
                domClass: 'dropload-down',
                domLoad: '<div class="dropload-load"><span class="loading dropload-loading"></span>加载中...</div>',
                domNoData: '<div class="dropload-noData">已经到底了</div>'
            },
            loadDownFn : function(me){
                page++;
                // 拼接HTML
                var result = '';
                $.ajax({
                    type: 'post',
                    url: 'index.php',
                    data: {page:page},
                    dataType: 'json',
                    success: function(res){
                        console.log(res,1111111111)
                        if(res.code == 200){
                            var data = res.data;
                            if(data.length!=0){
                                for(var i=0; i<data.length; i++){
                                    result += "<li class='opacity'>" +
                                    "<a href='content.php?id="+escape(data[i].id)+"'>" +
                                    "<div style='position: relative;'>" +
                                    "<img src='"+data[i].linkurl+"?vframe/jpg/offset/1/w/368/h/640/rotate/auto' class=''>" +
                                    "<p style='position: absolute;bottom: 0px;'>" +
                                    getCont(data[i].lng,data[i].lat,data[i].id) +
                                    "</p>" +
                                    "</div>" +
                                    "<h2 style='font-size: 11px;text-align: left;line-height: 30px;'>" + data[i].webnote + "</h2>" +
                                    "<div class='video-desc'>" +
                                    "<div class='fl' style='width: 70%;height: 25px;overflow: hidden;'>" +
                                    "<img src='"+data[i].avatar+"'>" +
                                    data[i].webname +
                                    "</div>"+
                                    "<em>"+ data[i].hits +"</em>" +
                                    "</div>" +
                                    "</a>" +
                                    "</li>";
                                }
                                // console.log(result)

                            }else{
                                // 锁定
                                me.lock();
                                // 无数据
                                me.noData();
                            }

                             // 插入数据到页面，放到最后面
                             setTimeout(() => {
                                $('.video-box .cl').append(result);
                                // 每次数据插入，必须重置
                                me.resetload();
                             }, 100);

                        }

                    },
                    error: function(xhr, type){
                        alert('Ajax error!');
                        // 即使加载出错，也得重置
                        me.resetload();
                    }
                });
            },
            threshold: 200
        });

    });

    function getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }

    function getaddre() {
        var map, geolocation;
        map = new AMap.Map('allmap');
        map.plugin('AMap.Geolocation', function () {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true //是否使用高精度定位，默认:true
            });
            geolocation.getCurrentPosition();
            AMap.event.addListener(geolocation, 'complete', function (point) {
                var p1 = [point.position.lng, point.position.lat];
                // alert(point.position.lng);
                // alert(point.position.lat);
                $("input[name='nearby_lat']").attr('value', point.position.lat);
                $("input[name='nearby_lng']").attr('value', point.position.lng);
//				var p1 = [120.637981,31.420484];
                $.each($(".julitxt"), function (k, v) {
                    if ($(this).attr("lng") != '' && $(this).attr("lat") != '') {
                        var p2 = [$(this).attr("lng"), $(this).attr("lat")];
                        var dis = AMap.GeometryUtil.distance(p1, p2);
                        var danwei;
                        if (dis > 1000) {
                            dis = dis / 1000;
                            dis = Math.round(dis);
                            danwei = 'km';
                        } else {
                            dis = Math.round(dis);
                            danwei = 'm';
                        }
                        $(this).html(dis + danwei);
                    }
                });
            });
        });
    }

    //搜索 首页重置
    function getSearch() {
        var seachKey = $("#keyword").val();
        if (seachKey == '' || seachKey.replace(/(^s*)|(s*$)/g, "").length == 0) {
            layer.open({
                content: '请输入搜索关键字！',
                skin: 'msg',
                time: 2 //2秒后自动关闭
            });
        } else {
            location.replace('https://5p8.fyh5p8.com/xiaochengxu/index.php?keyword=' + seachKey);
        }
    }

    //分享点击图片选择
    function upFile() {
        $('#file').click();
    }

    //图片改变
    function changepic(obj) {
        // $('#fileImg').removeClass('fileIcon').addClass('newImg');
        if (!obj.files || !obj.files[0]) {
            return;
        }

        // 找到canvas,准备画图
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');


        file = obj.files[0];
        console.log(file)
        // console.log('file', file)


        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (evt) {
            // console.log(reader.result);
            // if (reader.result.size > 2048) {
            //     layer.open({
            //         content: '文件大小需在2M以内！',
            //         skin: 'msg',
            //         time: 2 //2秒后自动关闭
            //     });
            // }

            //获取的是图片的base64代码
            var replaceSrc = evt.target.result;
            //定义一个Image对象
            var image = new Image();
            image.src = replaceSrc;
            image.onload = function () {
                //获取的是图片的base64代码
                var replaceSrc = evt.target.result;

                //定义一个Image对象
                var image = new Image();
                image.src = replaceSrc;
                image.onload = function () {

                    // 加载完毕后获取图片的原始尺寸
                    var origin_width = this.width;
                    var origin_height = this.height;
                    // console.log("原始图片宽度：" + origin_width + " px");
                    // console.log("原始图片高度：" + origin_height + " px");
                    // 设置最大允许宽高,根据需求自己设置,值越大,图片大小越大
                    var max_width = 100;
                    var max_height = 100;

                    // 最终宽高
                    target_width = origin_width;
                    target_height = origin_height;
                    if (origin_width > max_width || origin_height > max_height) {
                        if (origin_width / origin_height > max_width / max_height) {
                            // 更宽，按照宽度限定尺寸
                            target_width = max_width;
                            target_height = Math.round(max_width * (origin_height / origin_width));
                        } else {
                            target_height = max_height;
                            target_width = Math.round(max_height * (origin_width / origin_height));
                        }
                    }

                    canvas.width = target_width;
                    canvas.height = target_height;
                    // 绘画到画布上
                    context.drawImage(image, 0, 0, target_width, target_height);

                    //此处得到的是blob对象,blob对象是在ie10及以上才兼容,在ios8_1_1上和iphoneSE上有兼容问题
                    // canvas.toBlob(function (res) {
                    //     console.log(res);
                    //     formData.append("file", res);
                    //     // formData.append("openid", openid);
                    // });

                    // 读取canvas的数据
                    var result = canvas.toDataURL();


                    var arr = result.split(','),
                        mime = arr[0].match(/:(.*?);/)[1], // 转成blob
                        bstr = atob(arr[1]),
                        n = bstr.length,
                        u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    aaa = new window.File([new Blob([u8arr], {
                        type: mime
                    })], 'test.jpeg', {
                        type: 'image/jpg,image/jpeg,image/png,image/PNG'
                    }) // 转成file
                    console.log('00', aaa)
                    // console.log('000formData:', formData)
                    // 得到的结果是base64位的字符串,拿到压缩后的值通过网络请求交给后台处理...
                    // 如果是blob对象,需要通过FormData对象发送
                    console.log('最终图片链接', result); //最终图片链接

                    //最终图片宽高
                    //console.log("压缩后图片宽度：" + target_width + " px");
                    //console.log("压缩后图片高度：" + target_height + " px");
                    // 再将获取值赋给img标签
                    // $('#fileImg').attr("src", result);

                    var formData = new FormData();
                    formData.append("file", aaa);
                    sendToSever(formData);
                }
            }
        }


    }

    //获取图片文件名
    function getFileName(o) {
        var pos = o.lastIndexOf("\\");
        return o.substring(pos + 1);
    }

    //上传图片
    function sendToSever(formData) {
        $.ajax({
            url: 'fileup_img.php',
            type: "post",
            data: formData,
            dataType: 'json',
            processData: false, // 使数据不做处理
            contentType: false, // 不要设置Content-Type请求头
            timeout: 10000,
            beforeSend: function () {
                lid = layer.open({
                    type: 2,
                    content: '提交中...',
                    shadeClose: false
                });
            },
            success: function (res) {
                if (res.status == 'y') {
                    layer.open({
                        content: res.info,
                        skin: 'msg',
                        time: 2 //2秒后自动关闭
                    });

                    _imgURL = "https://5p8.fyh5p8.com/xiaochengxu/" + res.src;
                    $('#fileImg').attr("src", _imgURL);
                } else {
                    layer.open({
                        content: res.info,
                        skin: 'msg',
                        time: 2 //2秒后自动关闭
                    });
                }
                // console.log(_img);
            },
            complete: function () {
                layer.close(lid);
            },
            error: function (XMLHttpRequest, textStatus) {
                layer.close(lid);
                if ('timeout' == textStatus) {
                    alert('请求接口超时！');
                } else {
                    alert(JSON.stringify(XMLHttpRequest))
                }
            }
        });
    }

    //保存提交
    function loadData() {
        var title = $('.title-input').val();
        var desc = $('.desc-input').val();

        var id = "<?php echo $rows[0]['id']; ?>";
        var u_id = "<?php echo $_SESSION['Member_info'][0]['id']; ?>";

        // console.log(id, desc, title, share_img, u_id);
        $.ajax({
            url: 'share.php',
            type: "post",
            data: {'img_url': _imgURL, 'desc': desc, 'title': title, 'id': id, 'u_id': u_id, 'link': _link},
            dataType: 'json',
            timeout: 10000,
            beforeSend: function () {
                lid = layer.open({
                    type: 2,
                    content: '提交中...',
                    shadeClose: false
                });
            },
            success: function (res) {
                console.log(res);
                layer.close(lid);
                // alert(res)
                if (res.status == 'y') {
                    layer.open({
                        type: 1,
                        title: false//不显示标题
                        ,
                        offset: "t" //右上角弹出
                        // ,id: 'layerDemo' + type //防止重复弹出
                        ,
                        content: "<div id='sharebox' style='padding: 30px 20px;'><span style='display: inline-block;margin-right: 10px;'>保存成功！确认后，点击右上角去分享</span></div>"
                        ,
                        btn: '确认'
                        ,
                        btnAlign: 'c' //按钮居中
                        ,
                        shade: 0.8
                        ,
                        shadeClose: false
                        ,
                        yes: function () {
                            layer.closeAll();
                            window.location.reload();  //页面重载
                        }
                    });
                } else {
                    layer.open({
                        content: res.info,
                        skin: 'msg',
                        time: 2 //2秒后自动关闭
                    });
                }
            },
            complete: function () {
                //layer.close(lid);
            },
            error: function (XMLHttpRequest, textStatus) {
                layer.close(lid);
                if ('timeout' == textStatus) {
                    alert('请求接口超时！');
                } else {
                    alert('系统错误，请刷新重试！')
                }
            }
        });

    }

    function getCont(a,b,id){
        // console.log('a:',a, " b:",b," id:",id)
        if(a != null && b != null && a != '' && b != ''){
            return "<img src='./images/adress.png' alt='' style='width: 25px;'>" + "<span id='juli"+id+"' class='julitxt' lng='"+a+"' lat='"+b+"' style='color: #fff;font-size: 12px;letter-spacing: 1px;'></span>"
        }else{
            return '';
        }
    }
    //截取地址栏参数
    // function getUrlKey(name){
    //     return (
    //         decodeURIComponent(
    //         (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
    //             location.href
    //         ) || [, ""])[1].replace(/\+/g, "%20")
    //         ) || null
    //     );
    // }
</script>

<script type="">
    if(window.navigator.userAgent == 'AndroidNative'){ // 原生app将用户id传送给原生
        var userid = '<?php echo $_SESSION['Member_info'][0]['id'] ?>'; //用户
        // javascript:android.getUid(userid);
        dsBridge.call("getUid", {userid: userid});
    } else if (window.navigator.userAgent == 'IosNative') {
        var userid = '<?php echo $_SESSION['Member_info'][0]['id'] ?>'; //用户
        dsBridge.call("getUid", {userid: userid});
        // window.webkit.messageHandlers.getUid.postMessage(userid);
    }
</script>

</body>
</html>
